<?php

declare(strict_types=1);

namespace app\middleware;

use app\api\service\DmjUserService;
use app\api\service\OilStoreService;
use think\Response;

class OilTokenCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     *
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // token校验 todo 是否需要判断
        $decryptInfo = invoke(OilStoreService::class)->decryptH5Token($request->header('cipher'), $request->header('apiVersion', '1.0.0'), $request->param('cnid'));
        if ($decryptInfo['code']) {
            return fail('校验不通过，'.$decryptInfo['msg']);
        }

        $decryptInfo = $decryptInfo['data'];

        // 判断 session cnid 是否和传递的 cnid 相同。不同的话表示用户是从其他 cnid 进来，相当于需要重新登录
        if (intval($request->user['platform']['app_id']) !== $decryptInfo['cnid'] || ($request->user['platform']['platform'] !== $decryptInfo['platform'])) {
            // 密文解析成功后
            if ($token = $request->header('Authorization', '')) {
                $user = invoke(DmjUserService::class)->oilUserLogin($request->user['mobile'], $decryptInfo['cnid'], $decryptInfo['platform'], $token);
                if ($user['code']) {
                    return fail('请先登录', 401);
                }
                $request->user = $user['data'];
            } else {
                return fail('请先登录', 401);
            }
        }

        return $next($request);
    }
}
